package com.gengzp.mq.common.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @ClassName JsonUtils
 * @Description json工具类
 * @Author gengzp
 * @Date 2025/6/8 15:37
 */
public class GengzpMqJsonUtils {

    private static final ObjectMapper objectMapper = initObjectMapper();

    private GengzpMqJsonUtils() {
    }

    private static ObjectMapper initObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.findAndRegisterModules();
        return objectMapper;
    }

    /**
     * 将对象转为json
     *
     * @param obj 对象
     * @return json
     */
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将json转换为对象
     *
     * @param json  json字符串
     * @param clazz 对象类
     * @return 对象
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将json转换为对象, 保留泛型
     *
     * @param json  json字符串
     * @param clazz 泛型类
     * @return 泛型对象
     */
    public static <T> T parseObjectWithGeneric(String json, TypeReference<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
